﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace Microsoft.OpportunityPortal
{
    public class Risks
    {
        public static bool ProcessCaseStudyEvent(SPItemEventProperties properties)
        {
            try
            {
                // Algo: Read all the risk items and take average of all the risk scores and  update it in Opportunity
                // Request

                // 1. Get the risk items and calculate the average
                SPList oppRisksList = properties.Web.Lists["Opportunity Risks"];
                SPList configRiskList = properties.Web.ParentWeb.Lists["Risk Configuration"];
                int count = 0;
                float avgScore = 0;

                foreach (SPListItem item in oppRisksList.Items)
                {
                    string impactValue = item["Impact"].ToString();
                    // Get lookup ID for the Risk Configuration list
                    int id = SPOperations.ReturnLookupID(impactValue);

                    // Get the Risk Score
                    SPListItem configRiskItem = configRiskList.GetItemById(id);
                    avgScore = avgScore + int.Parse(configRiskItem["Score"].ToString());
                    count++;
                }

                if (count > 0)
                {
                    avgScore = avgScore / count;

                    // Update the risk score in Opportunity request list
                    // Get the Opportunity ID. Site URL and Opportunity ID will be the same
                    string url = properties.Web.Url;
                    string oppID = url.Substring(url.LastIndexOf('/') + 1);

                    // Get list instance
                    SPList oppReqList = properties.Web.ParentWeb.Lists["Opportunity Requests"];

                    SPQuery query = new SPQuery();
                    query.Query = string.Format(@"<Where><Eq><FieldRef Name=""Title"" /><Value Type=""Text"">{0}</Value></Eq></Where>", oppID);
                    SPListItemCollection itemColln = oppReqList.GetItems(query);

                    if (itemColln.Count > 0)
                    {
                        SPListItem item = itemColln[0];
                        item["Average Risk Score"] = avgScore;
                        item.Update();
                    }
                }
            }
            catch (Exception expn)
            {
                Dictionary<string, string> errorLog = new Dictionary<string, string>();
                errorLog.Add("Title", "Error_" + DateTime.Now.ToLongTimeString());
                errorLog.Add("Description", expn.Message);
                errorLog.Add("EventType", "Error");

                SPOperations.AddUpdateListItem(properties.WebUrl, "Logger", errorLog, SPEventType.Add);
                return false;
            }

            return true;
        }
    }
}
